//
//  PersonSetViewController.m
//  XDCommonApp
//
//  Created by wanglong8889@126.com on 14-3-7.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "PersonSetViewController.h"
#import "ChangePassWordViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "Base64.h"
#import "ChangePhoneViewController.h"
#import "UIImageView+WebCache.h"
#import "GuanYuViewController.h"
@interface PersonSetViewController ()
{
    NSUserDefaults *Defaults;
    NSString *portal;

    UIView *lineView;
}
@end

@implementation PersonSetViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.titleLabel.text = @"个人设置";
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    Defaults = [NSUserDefaults standardUserDefaults];
    
    lab = [[UILabel alloc] initWithFrame:CGRectMake(186, 12, 100, 20)];
    lab.text = @"010-59472975";
    lab.backgroundColor = [UIColor clearColor];
    lab.font = [UIFont systemFontOfSize:15.0];
     oldVerson = [[NSString alloc] initWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [self initViews];
	// Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector (mytest:) name:@"postData" object:nil];
}
-(void)initViews{
    headerView = [[UIImageView alloc] initWithFrame:CGRectMake(21, 15, 55, 55)];
    headerView.image = [UIImage imageNamed:@"personal_setting"];
    
    UIButton *addHeadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addHeadBtn setTitle:@"修改头像" forState:UIControlStateNormal];
    [addHeadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    addHeadBtn.frame = CGRectMake(headerView.frame.origin.x+headerView.frame.size.width+10,headerView.frame.origin.y, 60, 15);
    [addHeadBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    addHeadBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [addHeadBtn addTarget:self action:@selector(addHeadAction) forControlEvents:UIControlEventTouchUpInside];
    
    nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(addHeadBtn.frame.origin.x+5, addHeadBtn.frame.origin.y+addHeadBtn.frame.size.height+20, 200, 18)];
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.font = [UIFont systemFontOfSize:15.0];
    nameLabel.text = @"";
    
    [self.contentView addSubview:headerView];
    [self.contentView addSubview:addHeadBtn];
    [self.contentView addSubview:nameLabel];
    
    UIButton *changeCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeCodeBtn setTitle:@"更改密码" forState:UIControlStateNormal];
    changeCodeBtn.frame = CGRectMake(addHeadBtn.frame.origin.x+addHeadBtn.frame.size.width+86+15, addHeadBtn.frame.origin.y, 55, 18);
    [changeCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    changeCodeBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [changeCodeBtn addTarget:self action:@selector(changeCodeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:changeCodeBtn];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(headerView.frame.origin.x,headerView.frame.origin.y+headerView.frame.size.height+45, 65, 15)];
    label1.text = @"绑定邮箱:";
    label1.backgroundColor = [UIColor clearColor];
    label1.font = [UIFont systemFontOfSize:15.0];
//    [self.contentView addSubview:label1];

    emailTf = [[UITextField alloc] initWithFrame:CGRectMake(label1.frame.origin.x+label1.frame.size.width+5, label1.frame.origin.y+4, 145, 12)];
    emailTf.text = @"";
    emailTf.font = [UIFont systemFontOfSize:13.0];
    emailTf.userInteractionEnabled = NO;
    
    UIButton *emailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [emailBtn setTitle:@"修改" forState:UIControlStateNormal];
    [emailBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    emailBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [emailBtn addTarget:self action:@selector(changeFirst) forControlEvents:UIControlEventTouchUpInside];
    emailBtn.frame = CGRectMake(emailTf.frame.origin.x+emailTf.frame.size.width+15, label1.frame.origin.y, 65, 15);
    
    
//    [self.contentView addSubview:emailTf];
//    [self.contentView addSubview:emailBtn];

    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(headerView.frame.origin.x, label1.frame.origin.y+label1.frame.size.height-30, 65, 15)];
    label2.text = @"绑定手机:";
    label2.backgroundColor = [UIColor clearColor];
    label2.font = [UIFont systemFontOfSize:15.0];
    [self.contentView addSubview:label2];
    
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phone"];
    phoneTf = [[UITextField alloc] initWithFrame:CGRectMake(label2.frame.origin.x+label2.frame.size.width+5, label2.frame.origin.y, emailTf.frame.size.width, 15)];
    phoneTf.text = phone;
    phoneTf.font = [UIFont systemFontOfSize:14.0];
    phoneTf.userInteractionEnabled = NO;

    UIButton *phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [phoneBtn setTitle:@"修改" forState:UIControlStateNormal];
    phoneBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [phoneBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [phoneBtn addTarget:self action:@selector(changeSecond) forControlEvents:UIControlEventTouchUpInside];
    phoneBtn.frame = CGRectMake(phoneTf.frame.origin.x+phoneTf.frame.size.width+15, label2.frame.origin.y, 65, 15);

    if ([phone rangeOfString:@"@"].location == NSNotFound) {
        phoneTf.text = phone;
        emailTf.text = @"";
//         [emailBtn setTitle:@"添加邮箱" forState:UIControlStateNormal];
//         [phoneBtn setTitle:@"修改" forState:UIControlStateNormal];
        sign = 1;
        
    }else{
        phoneTf.text = @"";
        emailTf.text = phone;

//        [emailBtn setTitle:@"修改" forState:UIControlStateNormal];
//        [phoneBtn setTitle:@"添加手机号" forState:UIControlStateNormal];

        sign = 0;
    }
    

    
    [self.contentView addSubview:phoneTf];
    [self.contentView addSubview:phoneBtn];
    
    
    tishiLanbel = [[UILabel alloc] initWithFrame:CGRectMake(120, self.contentView.frame.size.height-40, 90, 15)];
    tishiLanbel.backgroundColor = [UIColor clearColor];
    tishiLanbel.textColor = [UIColor grayColor];
    tishiLanbel.text = @"上拉退出登录";
    tishiLanbel.font = [UIFont systemFontOfSize:14.0];
    [self.contentView addSubview:tishiLanbel];
    
    logOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    logOutBtn.frame = CGRectMake(0, self.contentView.frame.size.height-10, 320, 40);
    [logOutBtn setBackgroundImage:[UIImage imageNamed:@"go_out_launch"] forState:UIControlStateNormal];
    [logOutBtn addTarget:self action:@selector(logOutBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.contentView addSubview:logOutBtn];
    UISwipeGestureRecognizer *swipUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeOutLaunchUp:)];
    [swipUp setDirection:UISwipeGestureRecognizerDirectionUp];
    [self.contentView addGestureRecognizer:swipUp];
    
    UISwipeGestureRecognizer *swipDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeOutLaunchUp:)];
    [swipDown setDirection:UISwipeGestureRecognizerDirectionDown];
    [self.contentView addGestureRecognizer:swipDown];
    
//    setTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, self.contentView.frame.size.height-233, 300, 180) style:UITableViewStyleGrouped];
    setTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, label2.frame.origin.y+label2.frame.size.height+50, 300, 185) style:UITableViewStylePlain];
    setTableView.delegate = self;
    setTableView.dataSource = self;
    setTableView.scrollEnabled = NO;
    setTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    setTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:setTableView];
    dataArrry = [NSMutableArray arrayWithObjects:@"版本更新",@"清除缓存",@"关于",nil];//@"找画客服热线",
    setTableView.rowHeight = 44.0;
  
    
    [self getNickName];
    
    
    
}
- (void)mytest:(NSNotification*)noti
{
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phone"];
    phoneTf.text = phone;
}
- (void)REFRESHPHONENUM{

//    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phone"];
//    phoneTf.text = phone;

}
-(void)getNickName{
    Defaults = [NSUserDefaults standardUserDefaults];
    NSString *uid_STR = [NSString stringWithFormat:@"%@",[Defaults valueForKey:kMY_USER_ID]];
    
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <GetUserInfo xmlns=\"http://tempuri.org/\">"
                          "<uid>%@</uid>"
                          "</GetUserInfo>",uid_STR];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:GETUSERINFO];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){

                    nameLabel.text = [responseDict objectForKey:@"uname"];
//                    NSUserDefaults *Defaults = [NSUserDefaults standardUserDefaults];
                    [Defaults    setObject:[responseDict objectForKey:@"uname"] forKey:@"nickName"];

                    NSString *headerUrl = [responseDict objectForKeyedSubscript:@"uheadurl"];
                    if (![headerUrl isKindOfClass:[NSNull class]]) {
                        headerUrl = [headerUrl stringByReplacingOccurrencesOfString:@"\/" withString:@"/"];
//                        [headerView setImageWithURL:[NSURL URLWithString:headerUrl]];
                        [self getImageGCD:headerUrl];

                    }
                    
                    
                }else{
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

}
-(void)getImageGCD:(NSString *)urlString{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
        UIImage *image = [UIImage imageWithData:data];
        
    dispatch_async(dispatch_get_main_queue(), ^{
        headerView.image = image;
    });
    });
}
-(void)changeOutLaunchUp:(UISwipeGestureRecognizer *)sender{
    if (sender.direction == UISwipeGestureRecognizerDirectionUp) {
        [UIView animateWithDuration:.3 animations:^{
            logOutBtn.frame = CGRectMake(0, self.contentView.frame.size.height-40, 320, 40);
        }];
    }else{
        [UIView animateWithDuration:.3 animations:^{
            logOutBtn.frame = CGRectMake(0, self.contentView.frame.size.height-10, 320, 40);
        }];
    }
    
  
}
//修改头像
-(void)addHeadAction{
    [self photoImageTapAction:@"上传照片"];
}
//更改密码
-(void)changeCodeAction{
    ChangePassWordViewController *forgetVC = [[ChangePassWordViewController alloc] init];
    [self.navigationController pushViewController:forgetVC animated:YES];
}
//退出登录

- (void)logOutBtnClicked:(id)sender
{DDLOG(@"logout");
//    NSMutableDictionary  *dic = [Defaults objectForKey:kMY_USERINFO];
//    [dic removeObjectForKey:kMY_USER_ID];
//    [Defaults setObject:dic forKey:kMY_USERINFO];
    for (UIButton * button in [[XDTabBarViewController sharedXDTabBarViewController].bgView subviews]){
        if ([button isKindOfClass:[UIButton class]]){
            if (button.tag == 10001+3){
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_notOn"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_on"] forState:UIControlStateHighlighted];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_on"] forState:UIControlStateDisabled];
                button.adjustsImageWhenHighlighted =NO;
            }
        }
    }
    [Defaults setObject:@"" forKey:kMY_USER_ID];
    DDLOG(@" log uid  = %@",[Defaults valueForKey:kMY_USER_ID]);
    //删除本地存储
    [self.navigationController popViewControllerAnimated:YES];
    [[XDTabBarViewController sharedXDTabBarViewController] setSelectedIndex:0];
    [[XDTabBarViewController sharedXDTabBarViewController] confirmSelectTabBar:0];
    
}
//注销接口
- (void)getLogoutXMLData{

    Defaults = [NSUserDefaults standardUserDefaults];
    NSString *uid_STR = [NSString stringWithFormat:@"%@",[[Defaults valueForKey:kMY_USERINFO] valueForKey:kMY_USER_ID]];
    
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <logOut xmlns=\"http://tempuri.org/\">"
                          "<userinfor>%@</userinfor>"
                          "</logOut>",uid_STR];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:LOGIN];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    DDLOG(@"res = %@",responseDict);
                    
                    [XDTools showTips:@"成功" toView:self.contentView];
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [XDTools showTips:@"失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

}
-(void)changeFirst{
    ChangePhoneViewController *phoneVC = [[ChangePhoneViewController alloc] init];
    phoneVC.singal = 0;
    if (sign == 0) {
        [self.navigationController pushViewController:phoneVC animated:YES];
    }

    
}
-(void)changeSecond{
    ChangePhoneViewController *phoneVC = [[ChangePhoneViewController alloc] init];
    phoneVC.singal = 1;
    if (sign == 1) {
        [self.navigationController pushViewController:phoneVC animated:YES];
    }
//    phoneTf.userInteractionEnabled = YES;
}


#pragma  mark ---------------ActionSheet ---------------
- (void)photoImageTapAction:(NSString *)title
{
    photoActionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [photoActionSheet showInView:self.contentView];
}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    DDLOG(@"buttonIndex = %d", buttonIndex);
    if (buttonIndex == 0) {
        [self selectIncameraAction];
    }else if (buttonIndex == 1){
        [self selectInPhotoAlbumAction];
    }
}

//从本地相机选取图片
- (void)selectInPhotoAlbumAction
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.navigationBar.tintColor = [UIColor blackColor];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //本地相机
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}

//照相选取图片
- (void)selectIncameraAction
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.navigationBar.tintColor = [UIColor blackColor];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}

#pragma mark ----------------imagePickerDelegate-----------------------------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    isPhotoHadEdit = YES;
    
    //获得编辑过的图片
    if (isHeaderPhoto) {
        //头像
        isHeaderPhoto = NO;
        UIImage * image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        headerView.image = [UIImage imageNamed:@"User_profile_default_detail_head"];
        [self upLoadImage:image];
        headerView.image = image;
    }else{
        //相册
        UIImage * image = [info objectForKey: @"UIImagePickerControllerOriginalImage"];
        [self upLoadImage:image];
        headerView.image = image;
    }
    
}

- (void)showProcessVC:(UIImage*)image
{
    //    ProcessImageViewController * processVC = [[ProcessImageViewController alloc]init];
    //    processVC.image = image;
    //    [self.navigationController pushViewController:processVC animated:YES];
}


#pragma mrke --------------------上传图片-----------------------
- (void)upLoadImage:(UIImage*)image
{
    //    [MobClick event:@"upload_image"];
    
    if (image ==nil) {
        return;
    }
    NSDate * date = [NSDate date];
    DDLOG(@"date:%@",date);
    double time = [date timeIntervalSince1970];
    int timex = time/1;
    NSString * postTime = [NSString stringWithFormat:@"%d",timex];
    DDLOG(@"postTime:%@",postTime);
    NSData *data = [XDTools compressImage:image];
    NSString * postImage = [Base64 encode:data];
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
    NSString * dataLength = [NSString stringWithFormat:@"%d",[data length]];
    DDLOG(@"dataLength:%@", dataLength);
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <UploadFile xmlns=\"http://tempuri.org/\">"
                          "<fs>%@</fs>"
                          "<FileName>%@</FileName>"
                          "</UploadFile>",postImage,[NSString stringWithFormat:@"%@.jpg",uid]];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:UPLOADFILE];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    portal = [responseDict objectForKey:@"url"];
                    [self changeHeaderPic];
                }else{
                    [XDTools showTips:@"头像上传失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
    
    
}

-(void)changeHeaderPic{
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <ChangePortal xmlns=\"http://tempuri.org/\">"
                          "<uid>%@</uid>"
                          "<password>%@</password>"
                          "<portal>%@</portal>"
                          "</ChangePortal>",[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID],[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_PASSWORD],portal];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:CHANGEPORTAL];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    [WLSingleton sharedManager].Uid = [responseDict objectForKey:@"Uid"];
                    [XDTools showTips:@"修改成功" toView:self.contentView];

                }else{
                    [XDTools showTips:@"修改头像失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
}
//UItableView代理

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 5;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *bagview = [[UIView alloc]init];
    bagview.frame = CGRectMake(10, 0, 300, 5);
    bagview.backgroundColor = RGBA(240, 240, 240, 1);
    return bagview;

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return dataArrry.count;
    if (section==0) {
        return 3;
    }else if(section==1){
        return 1;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section==0) {
        NSString *cellIdentifer = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
            lineView = [[UIView alloc] initWithFrame:CGRectMake(15,44-1, 320-52, 1.0)];
            lineView.backgroundColor = RGBA(190, 190, 190, 1.0);
            UIImageView *arrowView1 = [[UIImageView alloc] initWithFrame:CGRectMake(267, 14.5, 10, 15)];
            arrowView1.image = [UIImage imageNamed:@"launh_sure"];
            arrowView1.tag = 100;
            [cell addSubview:arrowView1];
            [cell addSubview:lineView];

            UIView * numSelectView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 300, 120)];
            numSelectView.backgroundColor = [UIColor whiteColor];
            numSelectView.layer.cornerRadius = 5.0;
            numSelectView.layer.borderWidth = 1;
            numSelectView.layer.borderColor = [UIColorFromRGB(0xe2e2e2) CGColor];
//            [_scrollView addSubview:numSelectView];
            [tableView setBackgroundView:numSelectView];

            [cell addSubview:lab];
            lab.hidden = YES;
            cell.backgroundColor = [UIColor clearColor];
            
        }
        if (indexPath.row==2) {
            lineView.hidden = YES;
        }
        cell.textLabel.text = [dataArrry objectAtIndex:indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0];
        return cell;

    }else
    {
        NSString *cellIdentifer = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
//            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15,44-1, 320-52, 1.0)];
//            lineView.backgroundColor = RGBA(190, 190, 190, 1.0);
//            UIImageView *arrowView1 = [[UIImageView alloc] initWithFrame:CGRectMake(267, 12, 15, 20)];
//            arrowView1.image = [UIImage imageNamed:@"launh_sure"];
//            arrowView1.tag = 100;
//            [cell addSubview:arrowView1];
////            [cell addSubview:lineView];

            [cell addSubview:lab];
            lab.hidden = YES;
            cell.backgroundColor = [UIColor clearColor];
        }
//        if (indexPath.row == 3) {
            lab.hidden = NO;
            UIImageView *a = (UIImageView *)[cell viewWithTag:100];
            a.hidden = YES;

//        }
        cell.textLabel.text = @"找画客服热线";
        //[dataArrry objectAtIndex:indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0];
        return cell;

    }
    return nil;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"dd indexpath = %@",indexPath);

    if (indexPath.section==0) {
        switch (indexPath.row) {
            case 0:
                [self updateVerson];
                break;
            case 1:
                [self clearDatas];
                break;
            case 2:
                [self goToGuanYu];
                break;
            default:
                break;
        }

    }else if (indexPath.section==1){

        switch (indexPath.row) {

            case 0:

                [self makeTele];
            default:
                break;
        }

    }

}
//版本更新
-(void)updateVerson{
    
    NSString *body = [NSString stringWithFormat:@" <CheckUpdate xmlns=\"http://tempuri.org/\">"
                      "</CheckUpdate>"];
    
    __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:CHECKUPDATE];
    if([XDTools NetworkReachable]){
        [request setCompletionBlock:^{
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                DDLOG(@"result  ---=%@",result);
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){

                    NSString *newVerson = [responseDict objectForKey:@"newVersionCode"];
                    downUrl = [responseDict objectForKey:@"downUrl"];
                    if ([newVerson isEqualToString:oldVerson]) {
                        [XDTools showTips:@"当前已是最新版本" toView:self.contentView];
                    }else{
                        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"版本有更新,去更新?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                        al.tag = 1000;
                        [al show];
                        //跳转网址
                    }
                }else{
                    
                }
                
                
            }
            
            
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            //        NSError *error = [request error];
            
        }];
        //[XDTools showProgress:self.contentView];
        [request startAsynchronous];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}
#pragma mark- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000){
        if (buttonIndex == 0) {
            NSURL *url = [NSURL URLWithString:downUrl];
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }else{
        if (buttonIndex == 0){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://010-59472975"]];
        }
    }
    
}
//清除缓存
-(void)clearDatas{
    [XDTools showTips:@"缓存已清除" toView:self.view];
    NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *files = [fileManager subpathsAtPath:docPath];
    NSError *error;
    for (NSString *path in files) {
        NSString *newPath=[docPath stringByAppendingPathComponent:path];
        if ([fileManager fileExistsAtPath:newPath]) {
            [fileManager removeItemAtPath:newPath error:&error];
        }
    }
}
//跳到关于
-(void)goToGuanYu{
    GuanYuViewController *guanVC = [[GuanYuViewController alloc] init];
    [self.navigationController pushViewController:guanVC animated:YES];
}
-(void)makeTele{

    UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否拨打电话?" delegate:self cancelButtonTitle:@"拨打" otherButtonTitles:@"取消", nil];
    [al show];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
